﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.DAL;
using WXYW.BLL;
using System.Web.Configuration;
using WXYW.Model;
using System.Text;

namespace WXYW
{
    public partial class FormNeedRepair : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindProduct();
            }
            
            // 避免重复提交，对按钮添加点击之后禁止处理程序
            applyUpgradeLinkButton.Attributes.Add("onclick", "if(WaitforDealing('" + applyUpgradeLinkButton.ClientID + "')){" + GetPostBackEventReference(applyUpgradeLinkButton) + "}else{return false;}");
            sparePartApplyLinkButton.Attributes.Add("onclick", "if(WaitforDealing('" + sparePartApplyLinkButton.ClientID + "')){" + GetPostBackEventReference(sparePartApplyLinkButton) + "}else{return false;}");
            returnFactoryLinkButton.Attributes.Add("onclick", "if(WaitforDealing('" + returnFactoryLinkButton.ClientID + "')){" + GetPostBackEventReference(returnFactoryLinkButton) + "}else{return false;}");
            saveQuatationLnkBtn.Attributes.Add("onclick", "if(WaitforDealing('" + saveQuatationLnkBtn.ClientID + "')){" + GetPostBackEventReference(saveQuatationLnkBtn) + "}else{return false;}");
            addQuatationBtn.Attributes.Add("onclick", "if(WaitforDealing('" + addQuatationBtn.ClientID + "')){" + GetPostBackEventReference(addQuatationBtn) + "}else{return false;}");
            saveMaintainLinkButton.Attributes.Add("onclick", "if(WaitforDealing('" + saveMaintainLinkButton.ClientID + "')){" + GetPostBackEventReference(saveMaintainLinkButton) + "}else{return false;}");            
        }

        #region 初始化绑定

        // 绑定维修产品列表
        private void BindProduct()
        {
            try
            {
                DropDownItemService dropDownItemService = new DropDownItemService();
                DropDownList1.Items.Clear();
                DropDownList1.Items.Add("请选择收费原因");
                List<DropDownItem> reasonList = dropDownItemService.GetAllChargeReason();
                foreach (DropDownItem reason in reasonList)
                {
                    DropDownList1.Items.Add(new ListItem(reason.Name, reason.Name));
                }

                ApplicationService service = new ApplicationService();
                ApplicationForm applicationForm = service.GetApplicationFormDetailByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                ViewState["Type"] = applicationForm.ApplicationType;
                rmaCodeLabel.Text = applicationForm.ApplicationCode;
                applyTimeLabel.Text = applicationForm.ApplicationDateTime.HasValue ? applicationForm.ApplicationDateTime.Value.ToString("yyyy-MM-dd") : "";
                runningNumberLabel.Text = applicationForm.RunningNumber;
                receiveTimeLabel.Text = applicationForm.ReceiveDateTime.HasValue ? applicationForm.ReceiveDateTime.Value.ToString("yyyy-MM-dd") : "";
                distributeTimeLabel.Text = applicationForm.DistributeDateTime.HasValue ? applicationForm.DistributeDateTime.Value.ToString("yyyy-MM-dd") : "";

                applyCompanyNameTxtBox.Text = applicationForm.User.FullName;
                mailAddressTxtBox.Text = applicationForm.User.UserAddress;
                applierEmailTxtBox.Text = applicationForm.User.UserEmail;
                applierFaxTxtBox.Text = applicationForm.User.UserFax;
                rmaLabel.Text = applicationForm.ApplicationCode;
                runningNumberLabel.Text = applicationForm.RunningNumber;
                statusLbl.Text = applicationForm.Status;
                applierMobilePhoneTxtBox.Text = applicationForm.User.UserMobilePhone;
                applierNameTxtBox.Text = applicationForm.User.ContactPerson;
                applierPhoneTxtBox.Text = applicationForm.User.UserPhone;
                ProviderNameTxtBox.Text = applicationForm.ProviderName;

                //查询产品备件归还信息
                SparePartApplyService spaService = new SparePartApplyService();
                List<SparePartApplyForm> spaForms = new List<SparePartApplyForm>();

                List<ApplicationProduct> products = new List<ApplicationProduct>();
                //绑定待修的产品
                if (ContextService.CurrentAccount.UserType.ID == (int)RoleType.Engineer ||
                    ContextService.CurrentAccount.UserType.ID == (int)RoleType.PlatformEngineer)
                {
                    productGridView.DataSource = applicationForm.ApplicationProduct.Where(p => p.DistributeDateTime.HasValue && p.User != null && p.User.UserID == ContextService.CurrentAccount.UserID).OrderBy(p=>p.ApplicationProductID).ToList(); ;
                    //不维修产品信息数据
                    NoRepareInfoGridView.DataSource = applicationForm.ApplicationProduct.Where(p => p.User != null && p.User.UserID == ContextService.CurrentAccount.UserID && p.IsDecideToRepair != null && p.IsDecideToRepair == false);
                }
                else
                {
                    productGridView.DataSource = applicationForm.ApplicationProduct.Where(p => p.DistributeDateTime.HasValue).OrderBy(p => p.ApplicationProductID);                    
                    //不维修产品信息数据
                    NoRepareInfoGridView.DataSource = applicationForm.ApplicationProduct.Where(p => p.User != null && p.IsDecideToRepair != null && p.IsDecideToRepair == false).OrderBy(p => p.ApplicationProductID);
                }

                productGridView.DataBind();
                NoRepareInfoGridView.DataBind();

                //查询显示产品的备件归还信息
                if (null != products)
                {
                    foreach (ApplicationProduct product in products)
                    {
                        SparePartApplyForm spa = spaService.GetSparePartApplyByApplicationProductID(product.ApplicationProductID);
                        if (null != spa)
                        {
                            if (!spa.ApplicationProductReference.IsLoaded)
                            {
                                spa.ApplicationProductReference.Load();
                            }
                            if (!spa.ApplicationProduct.ProductTypeReference.IsLoaded)
                            {
                                spa.ApplicationProduct.ProductTypeReference.Load();
                            }
                            spaForms.Add(spa);
                        }
                    }
                }
                SparePartRtnInfoGridView.DataSource = spaForms;
                SparePartRtnInfoGridView.DataBind();

                if (!applicationForm.ApplicationPicture.IsLoaded)
                {
                    applicationForm.ApplicationPicture.Load();
                }
                //List<ApplicationPicture> picturelist = applicationForm.ApplicationPicture.Where(p => p.Type == (int)PictureType.ConfirmProduct || p.Type == (int)PictureType.MaintainProduct).ToList();
                List<ApplicationPicture> picturelist = applicationForm.ApplicationPicture.ToList();
                Table table = new Table();
                table.Rows.Add(new TableRow());
                table.Rows.Add(new TableRow());
                foreach (ApplicationPicture picture in picturelist)
                {
                    TableCell celllImage = new TableCell();
                    Image imageControl = new Image();
                    imageControl.Height = 100;
                    imageControl.ImageUrl = "Picture/" + picture.PictureNameOnServer;
                    imageControl.Attributes.Add("OnClick", "window.open('ImageDetail.aspx?Name=" + picture.PictureNameOnServer + "')");
                    celllImage.Controls.Add(imageControl);
                    table.Rows[0].Cells.Add(celllImage);

                    TableCell cellName = new TableCell();
                    Label label = new Label();
                    label.Text = picture.PictureName;
                    cellName.Controls.Add(label);
                    table.Rows[1].Cells.Add(cellName);
                }
                picturePanel.Controls.Add(table);

                // 如果有二次维修的，绑定维修记录
                ApplicationProductService productservice = new ApplicationProductService();
                List<MaintainHistoryModel> maintainHistoryList = productservice.GetApplicationProductHistoryByApplicatonFormID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                Label historyPromptLbl = maintainHistoryPanel.FindControl("historyPromptLbl") as Label;
                foreach (MaintainHistoryModel str in maintainHistoryList)
                {
                    historyPromptLbl.Visible = true;
                    HyperLink link = new HyperLink();
                    link.NavigateUrl = string.Format("MaintainRecordDetail.aspx?{0}={1}", Constants.QUERYSTR_PRODUCT_ID, str.ID);
                    link.Target = "_bank";
                    link.Text = str.SerialNumber+";  ";
                    maintainHistoryPanel.Controls.Add(link);
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::BindProduct");
                throw ex;
            }
        }

        // 产品绑定处理事件
        protected void productGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.DataItem != null)
                {
                    e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                    ((LinkButton)e.Row.FindControl("IDLbl")).Text = (e.Row.RowIndex + 1).ToString();

                    ApplicationProduct product = e.Row.DataItem as ApplicationProduct;
                    //Label isDecitdeToRepair = (Label)e.Row.FindControl("isDecideToRepairLiteral");
                    Label isQuotePrice = (Label)e.Row.FindControl("isQuotePriceLiteral");
                    LinkButton quotePriceLinkButton = (LinkButton)e.Row.FindControl("quotePriceLinkButton");
                    LinkButton maintainLinkButton = (LinkButton)e.Row.FindControl("repairLinkButton");
                    LinkButton upgradeLnkBtn = (LinkButton)e.Row.FindControl("upGridLinkButton");
                    LinkButton returnFactoryLnkBtn = (LinkButton)e.Row.FindControl("returnTofactoryLinkButton");
                    LinkButton sparePartLnkBtn = (LinkButton)e.Row.FindControl("sparePartLinkButton");
                    LinkButton repairLinkButton = (LinkButton)e.Row.FindControl("repairLinkButton");
                    LinkButton quoteCompleteLnkBtn = (LinkButton)e.Row.FindControl("quoteCompleteLnkBtn");
                    LinkButton repairCompleteLnkBtn = (LinkButton)e.Row.FindControl("repairCompleteLnkBtn");        

                    Label statusLbl = (Label)e.Row.FindControl("statusLbl");
                    // DOA 单不报价
                    if (ViewState["Type"].ToString().Equals("D"))
                    {
                        quotePriceLinkButton.Enabled = false;
                    }
                    
                    if(!product.UpgradeForm.IsLoaded)
                    {
                        product.UpgradeForm.Load();
                    }
                    if(!product.ReturnToFactoryForm.IsLoaded)
                    {
                        product.ReturnToFactoryForm.Load();
                    }
                    if (!product.SparePartApplyForm.IsLoaded)
                    {
                        product.SparePartApplyForm.Load();
                    }
                    if(!product.ApplicationFormReference.IsLoaded)
                    {
                        product.ApplicationFormReference.Load();
                    }

                    #region 显示维修状态及Tooltip, 设置与维修状态相关的按钮状态
                    string status = "";
                    string tooltip = "";

                    #region 升级申请单
                    if (product.UpgradeForm.Count > 0)
                    {
                        // 升级前已经报过价并已确认，不能再报价
                        if (product.ApplicationForm.ConfirmQuatationCompleteDate.HasValue)
                        {
                            quotePriceLinkButton.Enabled = false;
                        }

                        UpgradeForm upgradeForm = product.UpgradeForm.FirstOrDefault();
                        tooltip = string.Format("升级申请时间：{0}，当前状态：{1}", upgradeForm.ApplyTime.Value.ToString("yyyy-MM-dd HH:mm"), upgradeForm.Status);
                        // 升级-不同意
                        if (upgradeForm.Status.Equals("升级-不同意"))
                        {
                            status = "升级驳回-待修";
                            tooltip += string.Format(", 驳回时间：{0}， 驳回原因:{1}", upgradeForm.CompleteTime.Value.ToString("yyyy-MM-dd HH:mm"), upgradeForm.Suggestion);
                        }
                        // 升级已经完成
                        else if (upgradeForm.Status.Equals("升级完毕") ||
                            upgradeForm.Status.Equals("升级-平台收货确认"))
                        {
                            status = "升级完毕";
                        }
                        else if (upgradeForm.Status.Equals("升级-待修"))
                        {
                            status = "升级-待修";
                        }
                        else
                        {
                            status = "升级申请中";

                            sparePartLnkBtn.Enabled = false;
                            returnFactoryLnkBtn.Enabled = false;
                            repairLinkButton.Enabled = false;
                            quotePriceLinkButton.Enabled = false;
                            quoteCompleteLnkBtn.Enabled = false;
                            repairCompleteLnkBtn.Enabled = false;

                            returnFactoryLnkBtn.ForeColor = System.Drawing.Color.DarkGray;
                            sparePartLnkBtn.ForeColor = System.Drawing.Color.DarkGray;
                            repairLinkButton.ForeColor = System.Drawing.Color.DarkGray;
                            quotePriceLinkButton.ForeColor = System.Drawing.Color.DarkGray;
                            quoteCompleteLnkBtn.ForeColor = System.Drawing.Color.DarkGray;
                            repairCompleteLnkBtn.ForeColor = System.Drawing.Color.DarkGray;

                            returnFactoryLnkBtn.Font.Strikeout = true;
                            sparePartLnkBtn.Font.Strikeout = true;
                            repairLinkButton.Font.Strikeout = true;
                            quotePriceLinkButton.Font.Strikeout = true;
                            quoteCompleteLnkBtn.Font.Strikeout = true;
                            repairCompleteLnkBtn.Font.Strikeout = true;
                        }

                        upgradeLnkBtn.Enabled = false;
                        upgradeLnkBtn.Font.Strikeout = true;
                        upgradeLnkBtn.ForeColor = System.Drawing.Color.Red;
                    }
                    #endregion
                    #region 返厂申请单
                    if (product.ReturnToFactoryForm.Count > 0)
                    {
                        ReturnToFactoryForm returnToFactoryForm = product.ReturnToFactoryForm.FirstOrDefault();

                        upgradeLnkBtn.Enabled = false;
                        sparePartLnkBtn.Enabled = false;
                        returnFactoryLnkBtn.Enabled = false;
                        repairLinkButton.Enabled = false;
                        quotePriceLinkButton.Enabled = false;
                        quoteCompleteLnkBtn.Enabled = false;
                        repairCompleteLnkBtn.Enabled = false;

                        returnFactoryLnkBtn.ForeColor = System.Drawing.Color.Red;
                        if (product.UpgradeForm.Count == 0)
                        {
                            upgradeLnkBtn.ForeColor = System.Drawing.Color.DarkGray;
                        }
                        sparePartLnkBtn.ForeColor = System.Drawing.Color.DarkGray;
                        repairLinkButton.ForeColor = System.Drawing.Color.DarkGray;
                        quotePriceLinkButton.ForeColor = System.Drawing.Color.DarkGray;                       
                        quoteCompleteLnkBtn.ForeColor = System.Drawing.Color.DarkGray;
                        repairCompleteLnkBtn.ForeColor = System.Drawing.Color.DarkGray;

                        returnFactoryLnkBtn.Font.Strikeout = true;
                        upgradeLnkBtn.Font.Strikeout = true;
                        sparePartLnkBtn.Font.Strikeout = true;
                        repairLinkButton.Font.Strikeout = true;
                        quotePriceLinkButton.Font.Strikeout = true;
                        quoteCompleteLnkBtn.Font.Strikeout = true;
                        repairCompleteLnkBtn.Font.Strikeout = true;


                        if (!string.IsNullOrEmpty(status))
                        {
                            status += ", ";
                            tooltip += ", ";
                        }
                        status += "返厂维修中";
                        tooltip += string.Format("返厂申请时间：{0}, 当前状态：{1}", returnToFactoryForm.ApplyDate.Value.ToString("yyyy-MM-dd HH:mm"), returnToFactoryForm.Status);
                    }
                    #endregion
                    #region 备件申请单
                    if (product.SparePartApplyForm.Count > 0)
                    {
                        SparePartApplyForm sparePartApplyForm = product.SparePartApplyForm.FirstOrDefault();
                        if (sparePartApplyForm.Status.Equals("备件-不同意"))
                        {
                            if (!string.IsNullOrEmpty(status))
                            {
                                status += ", ";
                            }
                            status += "备件驳回-待修";
                        }
                        else if (sparePartApplyForm.Status.Equals("备件-已归还"))
                        {
                            if (!string.IsNullOrEmpty(status))
                            {
                                status += ", ";
                            }
                            status += "备件已归还-待修";
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(status))
                            {
                                status += ", ";
                            }
                            status += "备件申请中";

                            returnFactoryLnkBtn.Enabled = false;
                            upgradeLnkBtn.Enabled = false;

                            if (product.ReturnToFactoryForm.Count == 0)
                            {
                                returnFactoryLnkBtn.ForeColor = System.Drawing.Color.DarkGray;
                            }
                            if (product.UpgradeForm.Count == 0)
                            {
                                upgradeLnkBtn.ForeColor = System.Drawing.Color.DarkGray;
                            }

                            returnFactoryLnkBtn.Font.Strikeout = true;
                            upgradeLnkBtn.Font.Strikeout = true;                           
                        }
                        sparePartLnkBtn.Enabled = false;
                        sparePartLnkBtn.ForeColor = System.Drawing.Color.Red;
                        sparePartLnkBtn.Font.Strikeout = true;

                        if (!string.IsNullOrEmpty(status))
                        {
                            tooltip += ", ";
                        }
                        tooltip += string.Format("备件申请时间：{0}, 当前状态:{1}", sparePartApplyForm.ApplyTime.Value.ToString("yyyy-MM-dd HH:mm"), sparePartApplyForm.Status);
                    }
                    #endregion

                    #region 设置维修完成状态相关按钮
                    if (string.IsNullOrEmpty(product.BLXX))
                    {
                        if (!(!string.IsNullOrEmpty(product.ReasonOfNotRepair) &&
                            !(product.IsDecideToRepair.HasValue && product.IsDecideToRepair.Value)))
                        {
                            repairCompleteLnkBtn.Enabled = false;
                            repairCompleteLnkBtn.ForeColor = System.Drawing.Color.DarkGray;
                            repairCompleteLnkBtn.Font.Strikeout = true;

                            repairLinkButton.ForeColor = System.Drawing.Color.Green;
                        }
                        else
                        {
                            upgradeLnkBtn.Enabled = false;
                            sparePartLnkBtn.Enabled = false;
                            returnFactoryLnkBtn.Enabled = false;
                            repairLinkButton.Enabled = false;
                        }
                    }
                    else
                    {
                        repairLinkButton.ForeColor = System.Drawing.Color.Orange;
                    }

                    if (product.RepairCompleteDateTime.HasValue)
                    {
                        upgradeLnkBtn.Enabled = false;
                        sparePartLnkBtn.Enabled = false;
                        returnFactoryLnkBtn.Enabled = false;
                        repairLinkButton.Enabled = false;
                        quotePriceLinkButton.Enabled = false;
                        quoteCompleteLnkBtn.Enabled = false;

                        repairLinkButton.ForeColor = System.Drawing.Color.Red;

                        returnFactoryLnkBtn.Font.Strikeout = true;
                        upgradeLnkBtn.Font.Strikeout = true;
                        sparePartLnkBtn.Font.Strikeout = true;
                        repairLinkButton.Font.Strikeout = true;
                        quotePriceLinkButton.Font.Strikeout = true;
                        quoteCompleteLnkBtn.Font.Strikeout = true;

                        repairCompleteLnkBtn.Font.Strikeout = true;
                        repairCompleteLnkBtn.Enabled = false;
                        repairCompleteLnkBtn.ForeColor = System.Drawing.Color.Red;

                        //if (product.SendBackTime.HasValue)
                        //{
                        //    repairCompleteLnkBtn.Font.Strikeout = true;
                        //    repairCompleteLnkBtn.Enabled = false;
                        //    repairCompleteLnkBtn.ForeColor = System.Drawing.Color.Red;
                        //}
                        //else
                        //{
                        //    repairCompleteLnkBtn.Text = "修改维修";
                        //    repairCompleteLnkBtn.OnClientClick = "";
                        //}
                        status = "维修完毕待发货";
                        if (product.SendBackTime.HasValue)
                        {
                            tooltip += "发货时间：" + product.SendBackTime.Value.ToString("yyyy-MM-dd HH:mm");
                            status = "已发货待客户收货确认";

                            if (product.ClientReceiveDateTime.HasValue)
                            {
                                tooltip += "收货时间：" + product.ClientReceiveDateTime.Value.ToString("yyyy-MM-dd HH:mm");
                                status = "客户已收货确认";
                            }
                        }
                    }
                    #endregion

                    // 显示维修状态及Tooltip
                    statusLbl.ForeColor = System.Drawing.Color.Red;
                    if (string.IsNullOrEmpty(status))
                    {
                        status = "待修";
                        statusLbl.ForeColor = System.Drawing.Color.Green;
                        tooltip = "派单时间："+product.DistributeDateTime.Value.ToString("yyyy-MM-dd HH:mm");
                    }
                    statusLbl.Text = status;
                    statusLbl.ToolTip = tooltip;

                    
                    #endregion

                    #region 显示报价状态，设置于报价相关的按钮状态
                    // （针对新数据，增加了ApplicationForm.QuatationDatetime） 报价状态
                    if (!(product.IsQuotePrice.HasValue && product.IsQuotePrice.Value))
                    {
                        isQuotePrice.ForeColor = System.Drawing.Color.Green;
                        if (product.Status.Equals("报价驳回-待修"))
                        {
                            isQuotePrice.Text = "报价驳回";
                        }
                        else
                        {
                            isQuotePrice.Text = "未报价";
                        }                       

                        quoteCompleteLnkBtn.Enabled = false;
                        quoteCompleteLnkBtn.ForeColor = System.Drawing.Color.Gray;
                        quoteCompleteLnkBtn.Font.Strikeout = true;
                    }
                    else if (product.IsQuotePrice.HasValue && !product.QuotationDateTime.HasValue)
                    {
                        isQuotePrice.ForeColor = System.Drawing.Color.OrangeRed;
                        isQuotePrice.Text = "报价中";
                        quotePriceLinkButton.ForeColor = System.Drawing.Color.Orange;
                    }
                    else if (product.IsQuotePrice.HasValue && product.QuotationDateTime.HasValue &&
                        !product.ApplicationForm.QuatationDatetime.HasValue)
                    {
                        isQuotePrice.Text = "报价完毕";
                        isQuotePrice.ForeColor = System.Drawing.Color.DarkBlue;
                        quotePriceLinkButton.Enabled = false;
                        quotePriceLinkButton.ForeColor = System.Drawing.Color.Red;
                        quotePriceLinkButton.Font.Strikeout = true;

                        //quoteCompleteLnkBtn.Enabled = false;
                        //quoteCompleteLnkBtn.ForeColor = System.Drawing.Color.Red;
                        //quoteCompleteLnkBtn.Font.Strikeout = true;

                        quoteCompleteLnkBtn.Text = "重新报价";
                        quoteCompleteLnkBtn.OnClientClick = "";
                    }
                    // 报价确认中
                    else if ( product.QuotationDateTime.HasValue &&
                         product.ApplicationForm.QuatationDatetime.HasValue &&
                        !product.ApplicationForm.ConfirmQuatationCompleteDate.HasValue)
                    {
                        if (!product.ConfirmQuotationDateTime.HasValue)
                        {
                            isQuotePrice.Text = "报价确认中";
                            isQuotePrice.ForeColor = System.Drawing.Color.Red;

                            upgradeLnkBtn.Enabled = false;
                            sparePartLnkBtn.Enabled = false;
                            returnFactoryLnkBtn.Enabled = false;
                            repairLinkButton.Enabled = false;
                            quotePriceLinkButton.Enabled = false;
                            quoteCompleteLnkBtn.Enabled = false;
                            repairCompleteLnkBtn.Enabled = false;

                            if (product.UpgradeForm.Count == 0)
                            {
                                upgradeLnkBtn.ForeColor = System.Drawing.Color.DarkGray;
                            }
                            if (product.ReturnToFactoryForm.Count == 0)
                            {
                                returnFactoryLnkBtn.ForeColor = System.Drawing.Color.DarkGray;
                            }
                            if (product.SparePartApplyForm.Count == 0)
                            {
                                sparePartLnkBtn.ForeColor = System.Drawing.Color.DarkGray;
                            }
                            repairLinkButton.ForeColor = System.Drawing.Color.DarkGray;
                            quotePriceLinkButton.ForeColor = System.Drawing.Color.Red;
                            quoteCompleteLnkBtn.ForeColor = System.Drawing.Color.Red;
                            repairCompleteLnkBtn.ForeColor = System.Drawing.Color.DarkGray;

                            returnFactoryLnkBtn.Font.Strikeout = true;
                            upgradeLnkBtn.Font.Strikeout = true;
                            sparePartLnkBtn.Font.Strikeout = true;
                            repairLinkButton.Font.Strikeout = true;
                            quotePriceLinkButton.Font.Strikeout = true;
                            quoteCompleteLnkBtn.Font.Strikeout = true;
                            repairCompleteLnkBtn.Font.Strikeout = true;                            
                        }
                        else
                        {
                            // 接受报价维修
                            if (product.IsDecideToRepair.HasValue && product.IsDecideToRepair.Value)
                            {
                                isQuotePrice.Text = "接受报价，待付款";
                                isQuotePrice.ForeColor = System.Drawing.Color.DarkGreen;

                                if (!product.ApplicationForm.GatheringReference.IsLoaded)
                                {
                                    product.ApplicationForm.GatheringReference.Load();
                                }
                                if (product.ApplicationForm.Gathering != null)
                                {
                                    isQuotePrice.Text = "已收款";
                                    isQuotePrice.ForeColor = System.Drawing.Color.DarkGreen;
                                }
                            }
                            else
                            {
                                isQuotePrice.Text = "不接受报价";
                                if (!string.IsNullOrEmpty(product.ReasonOfNotRepair))
                                {
                                    isQuotePrice.Text = product.ReasonOfNotRepair;
                                }
                                isQuotePrice.ForeColor = System.Drawing.Color.DarkRed;
                                isQuotePrice.Font.Underline = true;
                            }

                            quotePriceLinkButton.Enabled = false;
                            quotePriceLinkButton.ForeColor = System.Drawing.Color.Red;
                            quotePriceLinkButton.Font.Strikeout = true;

                            quoteCompleteLnkBtn.Enabled = false;
                            quoteCompleteLnkBtn.ForeColor = System.Drawing.Color.Red;
                            quoteCompleteLnkBtn.Font.Strikeout = true;
                        }
                    }
                    // 已确认报价
                    else if (product.ApplicationForm.ConfirmQuatationCompleteDate.HasValue)
                    {
                        // 接受报价维修
                        if (product.IsDecideToRepair.HasValue && product.IsDecideToRepair.Value)
                        {
                            isQuotePrice.Text = "接受报价，待付款";
                            isQuotePrice.ForeColor = System.Drawing.Color.DarkGreen;

                            if (!product.ApplicationForm.GatheringReference.IsLoaded)
                            {
                                product.ApplicationForm.GatheringReference.Load();
                            }
                            if (product.ApplicationForm.Gathering != null)
                            {
                                isQuotePrice.Text = "已收款";
                                isQuotePrice.ForeColor = System.Drawing.Color.DarkGreen;
                            }
                        }
                        else
                        {
                            isQuotePrice.Text = "不接受报价";
                            if (!string.IsNullOrEmpty(product.ReasonOfNotRepair))
                            {
                                isQuotePrice.Text = product.ReasonOfNotRepair;
                            }
                            
                            isQuotePrice.ForeColor = System.Drawing.Color.DarkRed;
                            isQuotePrice.Font.Underline = true;
                        }                        

                        quotePriceLinkButton.Enabled = false;
                        quotePriceLinkButton.ForeColor = System.Drawing.Color.Red;
                        quotePriceLinkButton.Font.Strikeout = true;

                        quoteCompleteLnkBtn.Enabled = false;
                        quoteCompleteLnkBtn.ForeColor = System.Drawing.Color.Red;
                        quoteCompleteLnkBtn.Font.Strikeout = true;                        
                    }

                    if (!product.ApplicationForm.ApplicationProduct.IsLoaded)
                    {
                        product.ApplicationForm.ApplicationProduct.Load();
                    }
                    if (product.ApplicationForm.ApplicationProduct.Where(p => p.IsQuotePrice.HasValue && p.IsQuotePrice.Value).Count() == 0)
                    {
                        sumbitQuoteLnkBtn.Enabled = false;
                        sumbitQuoteLnkBtn.Font.Strikeout = true;
                        sumbitQuoteLnkBtn.ForeColor = System.Drawing.Color.Red;
                        if (sumbitQuoteLnkBtn.Text.Equals("提交整单报价"))
                        {
                            sumbitQuoteLnkBtn.Text += "（无报价）";
                            sumbitQuoteLnkBtn.OnClientClick = "";
                        }
                    }
                    if (product.ApplicationForm.QuatationDatetime.HasValue)
                    {
                        sumbitQuoteLnkBtn.Enabled = false;
                        sumbitQuoteLnkBtn.Font.Strikeout = true;
                        sumbitQuoteLnkBtn.ForeColor = System.Drawing.Color.Red;
                        if (sumbitQuoteLnkBtn.Text.Equals("提交整单报价"))
                        {
                            sumbitQuoteLnkBtn.Text += "（已提交）";
                            sumbitQuoteLnkBtn.OnClientClick = "";
                        }
                    }

                    if (product.QuotationDateTime.HasValue)
                    {
                        isQuotePrice.ToolTip = "报价时间：" + product.QuotationDateTime.Value.ToString("yyyy-MM-dd HH:mm");
                    }
                    if (product.ConfirmQuotationDateTime.HasValue)
                    {
                        isQuotePrice.ToolTip += "， 客户确认时间：" + product.ConfirmQuotationDateTime.Value.ToString("yyyy-MM-dd HH:mm");
                    }
                    
                    if (!product.ApplicationForm.GatheringReference.IsLoaded)
                    {
                        product.ApplicationForm.GatheringReference.Load();
                    }
                    if (product.ApplicationForm.Gathering != null)
                    {
                        isQuotePrice.ToolTip += "， 收款时间：" + product.ApplicationForm.Gathering.PayDateTime.Value.ToString("yyyy-MM-dd HH:mm");
                    }

                    if (!repairCompleteLnkBtn.Enabled)
                    {
                        repairCompleteLnkBtn.OnClientClick = "";
                    }
                    if (!quoteCompleteLnkBtn.Enabled)
                    {
                        quoteCompleteLnkBtn.OnClientClick = "";
                    }
                    #endregion
                    
                    #region 老代码
                    //if (product.UpgradeForm.Where(u => u.DistributeTime.HasValue && product.QuotationDateTime.HasValue && u.DistributeTime > product.QuotationDateTime).Count() > 0)
                    //{
                    //    quotePriceLinkButton.Visible = false;
                    //}
                    //switch (product.Status)
                    //{
                    //    case "报价确认中":
                    //        if (product.SparePartApplyForm.Count > 0)
                    //        {
                    //            if (!product.SparePartApplyForm.FirstOrDefault().Status.Equals("备件-已归还"))
                    //            {
                    //                returnFactoryLnkBtn.Enabled = false;
                    //                upgradeLnkBtn.Enabled = false;
                    //                sparePartLnkBtn.Enabled = false;
                    //            }
                    //        }
                    //        break;
                    //    case "备件申请中":
                    //        returnFactoryLnkBtn.Enabled = false;
                    //        upgradeLnkBtn.Enabled = false;
                    //        sparePartLnkBtn.Enabled = false;

                    //        returnFactoryLnkBtn.ForeColor = System.Drawing.Color.DarkGray;                         
                    //        upgradeLnkBtn.ForeColor = System.Drawing.Color.DarkGray;  
                    //        sparePartLnkBtn.ForeColor = System.Drawing.Color.Red;

                    //        returnFactoryLnkBtn.Font.Strikeout = true;
                    //        upgradeLnkBtn.Font.Strikeout = true;
                    //        sparePartLnkBtn.Font.Strikeout = true;
                    //        break;
                    //    case "升级-待审批": //过时，2013.8.31以后升级时状态统一改为升级申请中
                    //        upgradeLnkBtn.Enabled = false;
                    //        returnFactoryLnkBtn.Enabled = false;

                    //        returnFactoryLnkBtn.ForeColor = System.Drawing.Color.DarkGray;                         
                    //        upgradeLnkBtn.ForeColor = System.Drawing.Color.Red;  

                    //        returnFactoryLnkBtn.Font.Strikeout = true;
                    //        upgradeLnkBtn.Font.Strikeout = true;
                    //        break;
                    //    case "升级申请中":
                    //        upgradeLnkBtn.Enabled = false;
                    //        returnFactoryLnkBtn.Enabled = false;
                    //        sparePartLnkBtn.Enabled = false;

                    //        returnFactoryLnkBtn.ForeColor = System.Drawing.Color.DarkGray;                         
                    //        upgradeLnkBtn.ForeColor = System.Drawing.Color.Red;
                    //        sparePartLnkBtn.ForeColor = System.Drawing.Color.DarkGray;

                    //        returnFactoryLnkBtn.Font.Strikeout = true;
                    //        upgradeLnkBtn.Font.Strikeout = true;
                    //        sparePartLnkBtn.Font.Strikeout = true;
                    //        break;
                    //    case "返厂维修中":
                    //        upgradeLnkBtn.Enabled = false;
                    //        sparePartLnkBtn.Enabled = false;
                    //        returnFactoryLnkBtn.Enabled = false;
                    //        repairLinkButton.Enabled = false;
                    //        quotePriceLinkButton.Enabled = false;

                    //        returnFactoryLnkBtn.ForeColor = System.Drawing.Color.Red;                         
                    //        upgradeLnkBtn.ForeColor = System.Drawing.Color.DarkGray;
                    //        sparePartLnkBtn.ForeColor = System.Drawing.Color.DarkGray;  
                    //        repairLinkButton.ForeColor = System.Drawing.Color.DarkGray;
                    //        quotePriceLinkButton.ForeColor = System.Drawing.Color.DarkGray;  

                    //        returnFactoryLnkBtn.Font.Strikeout = true;
                    //        upgradeLnkBtn.Font.Strikeout = true;
                    //        sparePartLnkBtn.Font.Strikeout = true;
                    //        repairLinkButton.Font.Strikeout = true;
                    //        quotePriceLinkButton.Font.Strikeout = true;
                    //        break;
                    //}
                    //if (!product.ReturnToFactoryForm.IsLoaded)
                    //{
                    //    product.ReturnToFactoryForm.Load();
                    //}
                    //if (product.ReturnToFactoryForm != null && product.ReturnToFactoryForm.Count > 0)
                    //{
                    //    upgradeLnkBtn.Enabled = false;
                    //    sparePartLnkBtn.Enabled = false;
                    //    returnFactoryLnkBtn.Enabled = false;
                    //    repairLinkButton.Enabled = false;
                    //    quotePriceLinkButton.Enabled = false;
                    //}
                    // 留下兼容以前的数据
                    //if (product.IsQuotePrice.HasValue && product.IsQuotePrice.Value == true)
                    //{
                    //    if (product.Status == "报价确认中")
                    //    {
                    //        quotePriceLinkButton.Enabled = false;
                    //    }
                    //    isQuotePrice.Text = "已报价";
                    //}
                    //else
                    //{
                    //    isQuotePrice.Text = "未报价";
                    //}
                    #endregion        
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::productGridView_RowDataBound");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息提取发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        // 产品序号点击处理事件
        protected void IDLbl_Click(object sender, EventArgs e)
        {

        }
        #endregion

        #region 返回、保存
        // 点击返回按钮处理事件
        protected void backLinkButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("ListFormNeedRepair.aspx");
        }

        // 提交整单报价
        protected void sumbitQuoteLnkBtn_Click(object sender, EventArgs e)
        {
            try
            {
                ApplicationService applicationService = new ApplicationService();
                ApplicationForm applicationForm = applicationService.GetApplicationFormByID(Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));

                if (!applicationForm.ApplicationProduct.IsLoaded)
                {
                    applicationForm.ApplicationProduct.Load();
                }
                if (applicationForm.ApplicationProduct.Where(p => p.IsQuotePrice.HasValue && p.IsQuotePrice.Value).Count() > 0)
                {
                    string invalidMsg = "";
                    foreach (ApplicationProduct applicationProduct in applicationForm.ApplicationProduct)
                    {
                        if (applicationProduct.IsQuotePrice.HasValue && applicationProduct.IsQuotePrice.Value)
                        {
                            if (!applicationProduct.QuotationDateTime.HasValue)
                            {
                                invalidMsg += applicationProduct.ProductSerialNumber + ", ";
                            }
                        }
                    }
                    if (string.IsNullOrEmpty(invalidMsg))
                    {
                        applicationForm.QuatationDatetime = DateTime.Now;
                        applicationForm.QuoteBy = ContextService.CurrentAccount.UserID;
                        applicationService.UpdateApplication(applicationForm);
                        // 给报价员发通知邮件
                        if (!applicationForm.UserReference.IsLoaded)
                        {
                            applicationForm.UserReference.Load();
                        }
                        EmailService.SendEmailToBJY(applicationForm.ApplicationCode, applicationForm.User.ContactPerson);
                        ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('操作成功，该单流转到“待客户报价确认”，请尽快联系客户确认报价信息。在客户确认之前，您将无法继续操作待确认的产品。');"), true);
                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('该单中{0}等产品有报价条目，但尚未完成报价，请检查确认是否需要报价，如果需要报价并已经完成报价，请点击相应产品后的“报价完毕”完成报价，然后重新点击“提交整单报价”。');", invalidMsg), true);
                    }
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('该单中没有产品报价，不能提交整单报价，如果需要报价，请先点击相应产品后的报价按钮填写报价信息，之后点击产品后的报价完毕，待所有产品报价完成，才可点击提交整单报价。');"), true);
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::quoteCompleteLnkBtn_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('提交过程中发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        // 单个产品报价完成
        protected void quoteCompleteLnkBtn_Click(object sender, EventArgs e)
        {
            try
            {
                LinkButton quoteCompleteLnkBtn = sender as LinkButton;
                ApplicationProductService applicationProductService = new ApplicationProductService();
                ApplicationProduct applicationProduct = applicationProductService.GetApplicationProductByID(Convert.ToInt64(quoteCompleteLnkBtn.CommandArgument));
                if (quoteCompleteLnkBtn.Text.Equals("报价完毕"))
                {                    
                    applicationProduct.QuotationDateTime = DateTime.Now;                    
                    applicationProductService.UpdateProduct(applicationProduct);
                    BindProduct();
                    ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('操作成功，该产品已完成报价。请待其它产品完成报价后，点击页面右上角的“提交整单报价”按钮，统一提交客户确认。在此之前，还可通过“重新报价”来修改报价信息。');"), true);
                }
                // 重新报价
                else
                {
                    applicationProduct.QuotationDateTime = null;
                    applicationProductService.UpdateProduct(applicationProduct);
                    BindProduct();
                    ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('操作成功，请点击“报价”按钮修改报价信息，注意一旦整单提交报价送客户确认，则不能再修改报价信息。因此点击报价完毕要慎重。');"), true);
                }             
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::quoteCompleteLnkBtn_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('提交过程中发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        // 提交整单维修完毕
        protected void completeFormRepairLnkBtn_Click(object sender, EventArgs e)
        {
            try
            {
                ApplicationService applicationService = new ApplicationService();
                ApplicationForm applicationForm = applicationService.GetApplicationFormByID(Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                if (!applicationForm.ApplicationProduct.IsLoaded)
                {
                    applicationForm.ApplicationProduct.Load();
                }
                if (!applicationForm.GatheringReference.IsLoaded)
                {
                    applicationForm.GatheringReference.Load();
                }
                string invalidMsg = "";
                foreach (ApplicationProduct applicationProduct in applicationForm.ApplicationProduct)
                {
                    if (!applicationProduct.RepairCompleteDateTime.HasValue)
                    {
                        invalidMsg += applicationProduct.ProductSerialNumber + ", ";
                    }                    
                }
                if (string.IsNullOrEmpty(invalidMsg))
                {
                    applicationForm.CompleteDateTime = DateTime.Now;
                    if (applicationForm.QuatationDatetime.HasValue && applicationForm.ConfirmQuatationCompleteDate.HasValue &&
                        applicationForm.ApplicationProduct.Where(p => p.IsDecideToRepair.HasValue && p.IsDecideToRepair.Value).Count() > 0 &&
                        applicationForm.Gathering == null)
                    {
                        applicationForm.Status = "待付款确认";
                        applicationService.UpdateApplication(applicationForm);
                        Response.Write(string.Format("<script language='JavaScript'> alert( '该单已完成维修，将流转至待付款确认，请通知客户及时交款，交款之后才可发货！');location.href= 'ListFormNeedRepair.aspx' </script>"));
                    }
                    else
                    {
                        applicationForm.Status = "维修完毕待发货";
                        applicationService.UpdateApplication(applicationForm);
                        Response.Write(string.Format("<script language='JavaScript'> alert( '该单已完成维修，将流转至维修完毕待发货，请及时发货并通知客户收货！');location.href= 'ListFormNeedRepair.aspx' </script>"));
                    }                    
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('该单中{0}等产品有未维修完成，请检查确认，如果需要已经维修完成，请点击相应产品后的“维修完毕”完成报价，然后重新点击“整单维修完毕”。');", invalidMsg), true);
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::completeFormRepairLnkBtn_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('提交过程中发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }
        
        // 单个产品维修完成
        protected void repairCompleteLnkBtn_Click(object sender, EventArgs e)
        {
            try
            {
                LinkButton repairCompleteLnkBtn = sender as LinkButton;
                ApplicationProductService applicationProductService = new ApplicationProductService();
                ApplicationProduct applicationProduct = applicationProductService.GetApplicationProductByID(Convert.ToInt64(repairCompleteLnkBtn.CommandArgument));
                                 
                if (applicationProduct.QuotationDateTime.HasValue && !applicationProduct.ConfirmQuotationDateTime.HasValue)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('该产品有报价，但是未提交客户确认，请您先提交报价待客户确认之后再点击该产品的维修完毕。如果不打算报价，请先删除报价信息之后再点维修完毕。');"), true);
                }
                else
                {
                    // 如果是升级的，更新升级申请单的状态
                    if (!applicationProduct.UpgradeForm.IsLoaded)
                    {
                        applicationProduct.UpgradeForm.Load();
                    }
                    if (applicationProduct.UpgradeForm.Count > 0)
                    {
                        UpgradeForm upgradeForm = applicationProduct.UpgradeForm.FirstOrDefault();
                        if (upgradeForm.SendWay == "平台")
                        {
                            upgradeForm.Status = "升级-完毕待发货";
                        }
                        else
                        {
                            upgradeForm.Status = "升级完毕";
                            upgradeForm.CompleteTime = DateTime.Now;
                        }
                        UpgradeService upgradeService = new UpgradeService();
                        upgradeService.Update(upgradeForm);
                    }
                    applicationProduct.RepairCompleteDateTime = DateTime.Now;

                    // 报价产品检查是否收款
                    if (applicationProduct.IsQuotePrice.HasValue && applicationProduct.QuotationDateTime.HasValue &&
                        applicationProduct.IsDecideToRepair.HasValue && applicationProduct.IsDecideToRepair.Value &&
                        applicationProduct.ConfirmQuotationDateTime.HasValue)
                    {
                        if (!applicationProduct.ApplicationForm.GatheringReference.IsLoaded)
                        {
                            applicationProduct.ApplicationForm.GatheringReference.Load();
                        }

                        if (applicationProduct.ApplicationForm.Gathering != null)
                        {
                            applicationProduct.Status = "维修完毕待发货";
                            applicationProductService.UpdateProduct(applicationProduct);
                            BindProduct();
                            ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('操作成功，该产品已维修完成。将流转至维修完毕待发货。');"), true);
                        }
                        else
                        {
                            applicationProduct.Status = "待付款确认";
                            applicationProductService.UpdateProduct(applicationProduct);
                            BindProduct();
                            ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('操作成功，该产品已维修完成。现等待收款。');"), true);
                        }
                    }
                    else
                    {
                        applicationProduct.Status = "维修完毕待发货";
                        applicationProductService.UpdateProduct(applicationProduct);
                        BindProduct();
                        ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('操作成功，该产品已维修完成。将流转至维修完毕待发货。');"), true);
                    }                    
                }      
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::repairCompleteLnkBtn_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('提交过程中发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        #region old code
        // 点击保存按钮处理事件
        //protected void okLinkButton_Click(object sender, EventArgs e)
        //{
        //    string changeLogContent = string.Format("");
        //    ChangeLogService changeLogService = new ChangeLogService();

        //    // 已填写完报价单的待修产品更新状态为“报价确认中”
        //    UpdateHaveQuatationedProduct();

        //    try
        //    {
        //        ApplicationProductService productServie = new ApplicationProductService();
        //        foreach (GridViewRow row in productGridView.Rows)
        //        {
        //            LinkButton maintainbutton = row.FindControl("repairLinkButton") as LinkButton;

        //            ApplicationProduct product = productServie.GetApplicationProductByID(long.Parse(maintainbutton.CommandArgument));
        //            if (!product.RepairCompleteDateTime.HasValue)
        //            {
        //                continue;
        //            }
        //            if (!product.UpgradeForm.IsLoaded)
        //            {
        //                product.UpgradeForm.Load();
        //            }
        //            if (!product.ReturnToFactoryForm.IsLoaded)
        //            {
        //                product.ReturnToFactoryForm.Load();
        //            }
        //            if (!product.SparePartApplyForm.IsLoaded)
        //            {
        //                product.SparePartApplyForm.Load();
        //            }

        //            // 没有申请升级、返厂、备件
        //            if (product.UpgradeForm.Count == 0 && product.ReturnToFactoryForm.Count == 0 && product.SparePartApplyForm.Count == 0)
        //            {
                        
        //            }

        //            //if (product.UpgradeForm.Count > 0 && product.UpgradeForm.Where(u => u.Status == "升级-待修").Count() > 0
        //            //    && product.Status.Contains("待修") && product.RepairCompleteDateTime.HasValue)
        //            //{
        //            //    UpgradeForm upgradeform = product.UpgradeForm.Where(u => u.Status == "升级-待修").FirstOrDefault();
        //            //    if (product.UpgradeForm.FirstOrDefault().SendWay.Equals("平台"))
        //            //    {
        //            //        upgradeform.Status = "升级-完毕待发货";
        //            //        product.Status = "升级-完毕待发货";
        //            //    }
        //            //    else
        //            //    {
        //            //        upgradeform.Status = "升级完毕";
        //            //        product.Status = "维修完毕待发货";
        //            //    }

        //            //    productServie.FinishMaintainProduct(product);
        //            //}
        //            //else if (product.ReturnToFactoryForm.Count > 0 && product.Status == "返厂维修完毕-待发货")
        //            //{
        //            //    product.Status = "维修完毕待发货";
        //            //    productServie.FinishMaintainProduct(product);
        //            //}
        //            //else if (product.SparePartApplyForm.Count > 0 && product.Status == "备件维修完毕-待修")
        //            //{
        //            //    product.Status = "维修完毕待发货";
        //            //    productServie.FinishMaintainProduct(product);
        //            //}
        //            //else if (product.UpgradeForm.Where(u => u.Status != "升级-不同意").Count() == 0 && product.ReturnToFactoryForm.Count == 0
        //            //    && !product.Status.Equals("维修完毕待发货"))
        //            //{
        //            //    product.Status = "维修完毕待发货";
        //            //    productServie.FinishMaintainProduct(product);
        //            //}
        //            //else if (product.Status.Equals("已确认-待修") && !string.IsNullOrEmpty(product.BLXX))
        //            //{
        //            //    product.RepairCompleteDateTime = DateTime.Now;
        //            //    product.Status = "维修完毕待发货";
        //            //    productServie.FinishMaintainProduct(product);
        //            //}
        //        }


        //        // 如果产品中有报价待确认的，而且没有待修的产品(如果是升级产品则直接到 报价确认)，刚表单为 报价确认中。
        //        ApplicationService service = new ApplicationService();
        //        ApplicationForm applicationForm = service.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
        //        if (applicationForm.ApplicationProduct.Where(p => p.Status == "报价确认中").Count() > 0 && applicationForm.ApplicationProduct.Where(p => p.Status == "待修").Count() == 0)
        //        {
        //            applicationForm.Status = "报价确认中";
        //            applicationForm.QuatationDatetime = DateTime.Now;
        //            service.UpdateApplication(applicationForm);
        //            if (!applicationForm.UserReference.IsLoaded)
        //            {
        //                applicationForm.UserReference.Load();
        //            }
        //            EmailService.SendEmailToBJY(applicationForm.ApplicationCode, applicationForm.User.ContactPerson);
        //        }

        //        Response.Write(string.Format("<script language='JavaScript'> alert( '记录已成功保存！');location.href= 'ListFormNeedRepair.aspx' </script>"));
        //    }
        //    catch (IndexOutOfRangeException ie)
        //    {
        //        LogUtility.LogUtilityIntance.LogException(ie, "FormNeedRepair.aspx::okLinkButton_Click");
        //        MsgLbl.Visible = true;
        //        MsgLbl.Text = "信息保存失败，请检查不良原因、不良零件、不良零件位置是否一一对应。";
        //    }
        //    catch (Exception ex)
        //    {
        //        LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair.aspx::okLinkButton_Click");
        //        throw ex;
        //    }
        //}

        //private void UpdateHaveQuatationedProduct()
        //{
        //    string changeLogContent = string.Format("");
        //    ChangeLogService changeLogService = new ChangeLogService();
        //    string dealwithProductID = "";
        //    try
        //    {
        //        List<ApplicationProduct> products = new List<ApplicationProduct>();
        //        ApplicationService service = new ApplicationService();
        //        ApplicationForm applicationForm = service.GetApplicationFormDetailByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
               
        //        if (ContextService.CurrentAccount.UserType.ID == (int)RoleType.Engineer ||
        //            ContextService.CurrentAccount.UserType.ID == (int)RoleType.PlatformEngineer)
        //        {
        //            products = applicationForm.ApplicationProduct.Where(p => p.User != null && p.User.UserID == ContextService.CurrentAccount.UserID && !p.Status.Equals("维修完毕待发货") && !p.RepairCompleteDateTime.HasValue).ToList();
        //        }
        //        else
        //        {
        //            products = applicationForm.ApplicationProduct.Where(p => p.User != null && !p.RepairCompleteDateTime.HasValue && p.DistributeDateTime.HasValue).ToList();
        //        }
        //        ApplicationProductService productservice = new ApplicationProductService();
        //        foreach (ApplicationProduct product in products)
        //        {
        //            if (!product.QuatationForm.IsLoaded)
        //            {
        //                product.QuatationForm.Load();
        //            }

        //            if (product.QuatationForm.Count > 0 && (!product.ConfirmQuotationDateTime.HasValue || !product.IsDecideToRepair.HasValue))
        //               //(product.Status.Contains("待修") || product.Status.Contains("升级") || product.Status.Contains("备件")))
        //            {
        //                dealwithProductID = product.ApplicationProductID.ToString();
        //                changeLogContent = string.Format("产品报价更新产品状态信息 UpdateHaveQuatationedProduct");
        //                changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, dealwithProductID, changeLogContent);

        //                product.Status = "报价确认中";

        //                if (!product.QuotationDateTime.HasValue)
        //                {
        //                    DateTime quoteDateTime = DateTime.Now;
        //                    foreach (QuatationForm quoteform in product.QuatationForm)
        //                    {
        //                        if (!quoteform.CreateDate.HasValue)
        //                        { 
        //                            quoteform.CreateDate = DateTime.Now;
        //                        }
        //                        else if (quoteform.CreateDate < quoteDateTime)
        //                        {
        //                            quoteDateTime = quoteform.CreateDate.Value;
        //                        }
        //                    }                            
        //                    product.QuotationDateTime = quoteDateTime;
        //                }
        //                product.IsQuotePrice = true; // 避免第一次未设置
        //                productservice.UpdateProduct(product);
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::UpdateHaveQuatationedProduct");

        //        changeLogContent = string.Format("产品报价更新产品状态信息异常 UpdateHaveQuatationedProduct：：{0}", ex.ToString());
        //        changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, dealwithProductID, changeLogContent);

        //        throw ex;
        //    }
        //}
        #endregion
        #endregion

        #region for maintain record
        // 点击维修按钮 显示维修记录对话框
        protected void maintainLinkButton_Click(object sender, EventArgs e)
        {
            string productID = ((LinkButton)sender).CommandArgument;
            hfproductID.Value = productID;
            maintainRecordModalPopupExtender.Show();
            ClearWXForm();
            BindProductInfo(Convert.ToInt64(productID));
        }

        // 点击维修记录对话框上的保存按钮
        protected void saveMaintainLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetSimpleApplicatonProductByID(long.Parse(hfproductID.Value));
                product.BLXX = blxxTextBox.Text;
                product.ReasonToProblem = getBLYY();
                product.RepairAccessory = getWXLJ();
                product.AccessoryPlace = getLJWZ();

                if (!string.IsNullOrEmpty(thSerialNumberTextBox.Text))
                {
                    product.ReplaceProductSerialNumber = thSerialNumberTextBox.Text;
                }
                if (!string.IsNullOrEmpty(thProductTypeTextBox.Text))
                {
                    product.ReplaceProductType = thProductTypeTextBox.Text;
                }
                if (versionDDL.SelectedIndex != 0)
                {
                    product.ReplaceProductVersion = versionDDL.SelectedValue;
                }
                if (thRadioButton.Checked)
                {
                    product.ChangeType = "替换";
                }
                if (ghRadioButton.Checked)
                {
                    product.ChangeType = "更换";
                }
                product.Remark = bzTextBox.Text;
                //product.RepairCompleteDateTime = DateTime.Now; // Chen Pu: 2010-06-02 不能在这里保存维修完成时间
                if (!product.ProblemAnalyzeReference.IsLoaded)
                {
                    product.ProblemAnalyzeReference.Load();
                }
                if (product.ProblemAnalyze == null)
                {
                    product.ProblemAnalyze = new ProblemAnalyze();
                }
                product.ProblemAnalyze.A = getProblemAnalyzeA();
                product.ProblemAnalyze.B = getProblemAnalyzeB();
                product.ProblemAnalyze.C = getProblemAnalyzeC();
                product.ProblemAnalyze.D = getProblemAnalyzeD();
                product.ProblemAnalyze.E = getProblemAnalyzeE();

                string valisdtaResult = string.Empty;
                valisdtaResult = ValidateMaintain();
                if (string.IsNullOrEmpty(valisdtaResult))
                {
                    #region commented code
                    /// 客户要求维修记录填写保存时 不能修改维修状态，只有点击页面保存按钮后才可以修改
                    /// 因此将这块代码移到页面保存按钮点击事件里
                    //if (!product.UpgradeForm.IsLoaded)
                    //{
                    //    product.UpgradeForm.Load();
                    //}
                    //if (product.UpgradeForm.Count > 0 && product.UpgradeForm.FirstOrDefault().SendWay.Equals("平台"))
                    //{
                    //    UpgradeForm upgradeform = product.UpgradeForm.FirstOrDefault();
                    //    upgradeform.Status = "升级-完毕待发货";
                    //    product.Status = "升级-完毕待发货";
                    //}
                    //else
                    //{
                    //    product.Status = "维修完毕待发货";
                    //}

                    //product.RepairCompleteDateTime = DateTime.Now; // 2013.8.31 注释 统一调用ApplicationProductService.CompleteApplicationProductRepair
            

                    //if (!product.ApplicationFormReference.IsLoaded)
                    //{
                    //    product.ApplicationFormReference.Load();
                    //}

                    //ApplicationService applicationService = new ApplicationService();
                    //if (applicationService.AllProductFinishRepair(product.ApplicationForm.ApplicationID))
                    //{
                    //    product.ApplicationForm.Status = "维修完毕待发货";
                    //}
                    #endregion

                    service.UpdateProduct(product);       
       
                    maintainRecordModalPopupExtender.Hide();
                    Response.Redirect(string.Format("FormNeedRepair.aspx?{0}={1}", Constants.QUERYSTR_APPLICATION_ID, Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                    
                    //ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('维修信息保存成功，待该产品维修完成，请点击该产品之后的“维修完毕”按钮，使该产品等待流转至下一流程。');"), true);
                }
                else
                {
                    Label1.Text = string.Format("维修信息保存失败，请按下列要求检查所填数据：{0}", valisdtaResult);
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::saveMaintainLinkButton_Click");
                Label1.Text = string.Format("信息保存发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}", ex.Message);
            }
        }


        protected void blxxTextBox_TextChanged(object sender, EventArgs e)
        {
            try
            {
                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetApplicationProductByID(long.Parse(hfproductID.Value));
                product.BLXX = blxxTextBox.Text;
                service.UpdateProduct(product);
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::blxxTextBox_TextChanged");
                throw ex;
            }
        }

        protected void thProductTypeTextBox_TextChanged(object sender, EventArgs e)
        {
            if (thRadioButton.Checked && !string.IsNullOrEmpty(thProductTypeTextBox.Text))
            {
                blljTextBox1.Text = "替换：" + thProductTypeTextBox.Text;
            }
        }

        protected void ghRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetApplicationProductByID(long.Parse(hfproductID.Value));
                if (!product.ProductTypeReference.IsLoaded)
                {
                    product.ProductTypeReference.Load();
                }
                blljTextBox1.Text = "替换：" + product.ProductType.ProductTypeName;
                thProductTypeTextBox.Text = "";
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::ghRadioButton_CheckedChanged");
                throw ex;
            }
        }

        protected void blyyRadioButtonList1_SelectedChanged(object sender, EventArgs e)
        {
            if (blyyRadioButtonList1.SelectedIndex == 0)
            {
                ljwzTextBox1.Text = "0";
                blljTextBox1.Text = "Retest ok";
            }
            else if (blyyRadioButtonList1.SelectedIndex == 3)
            {
                ljwzTextBox1.Text = "0";
                blljTextBox1.Text = "软件升级";
            }
        }

        protected void blyyRadioButtonList2_SelectedChanged(object sender, EventArgs e)
        {
            if (blyyRadioButtonList2.SelectedIndex == 0)
            {
                ljwzTextBox2.Text = "0";
                blljTextBox2.Text = "Retest ok";
            }
            else if (blyyRadioButtonList1.SelectedIndex == 3)
            {
                ljwzTextBox2.Text = "0";
                blljTextBox2.Text = "软件升级";
            }
        }

        protected void blyyRadioButtonList3_SelectedChanged(object sender, EventArgs e)
        {
            if (blyyRadioButtonList3.SelectedIndex == 0)
            {
                ljwzTextBox3.Text = "0";
                blljTextBox3.Text = "Retest ok";
            }
            else if (blyyRadioButtonList1.SelectedIndex == 3)
            {
                ljwzTextBox3.Text = "0";
                blljTextBox3.Text = "软件升级";
            }
        }

        protected void blyyRadioButtonList4_SelectedChanged(object sender, EventArgs e)
        {
            if (blyyRadioButtonList4.SelectedIndex == 0)
            {
                ljwzTextBox4.Text = "0";
                blljTextBox4.Text = "Retest ok";
            }
            else if (blyyRadioButtonList4.SelectedIndex == 3)
            {
                ljwzTextBox4.Text = "0";
                blljTextBox4.Text = "软件升级";
            }
        }

        protected void blyyRadioButtonList5_SelectedChanged(object sender, EventArgs e)
        {
            if (blyyRadioButtonList5.SelectedIndex == 0)
            {
                ljwzTextBox5.Text = "0";
                blljTextBox5.Text = "Retest ok";
            }
            else if (blyyRadioButtonList4.SelectedIndex == 3)
            {
                ljwzTextBox5.Text = "0";
                blljTextBox5.Text = "软件升级";
            }
        }

        protected void clearReasonLinkButton_Click(object sender, EventArgs e)
        {
            blyyRadioButtonList1.SelectedIndex = -1;
            blyyRadioButtonList2.SelectedIndex = -1;
            blyyRadioButtonList3.SelectedIndex = -1;
            blyyRadioButtonList4.SelectedIndex = -1;
            blyyRadioButtonList5.SelectedIndex = -1;
        }

        protected void clearAnalyseLinkButton_Click(object sender, EventArgs e)
        {
            RadioButton1.Checked = false;
            RadioButton2.Checked = false;
            RadioButton3.Checked = false;
            RadioButton4.Checked = false;
            RadioButton5.Checked = false;
            RadioButton6.Checked = false;
            RadioButton7.Checked = false;
            RadioButton8.Checked = false;
            RadioButton9.Checked = false;
            RadioButton10.Checked = false;
            RadioButton11.Checked = false;
            RadioButton12.Checked = false;
            RadioButton13.Checked = false;
            RadioButton14.Checked = false;
            RadioButton15.Checked = false;
            RadioButton16.Checked = false;
        }

        protected void bzTextBox_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(bzTextBox.Text))
                {
                    ApplicationProductService service = new ApplicationProductService();
                    ApplicationProduct product = service.GetApplicationProductByID(long.Parse(hfproductID.Value));
                    product.Remark = bzTextBox.Text;

                    service.UpdateProduct(product);
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::bzTextBox_TextChanged");
                throw ex;
            }
        }        

        private void ClearWXForm()
        {
            blxxTextBox.Text = "";
            blyyRadioButtonList1.ClearSelection();
            blyyRadioButtonList2.ClearSelection();
            blyyRadioButtonList3.ClearSelection();
            blyyRadioButtonList4.ClearSelection();
            blyyRadioButtonList5.ClearSelection();
            blljTextBox1.Text = "";
            blljTextBox2.Text = "";
            blljTextBox3.Text = "";
            blljTextBox4.Text = "";
            blljTextBox5.Text = "";
            ljwzTextBox1.Text = "";
            ljwzTextBox2.Text = "";
            ljwzTextBox3.Text = "";
            ljwzTextBox4.Text = "";
            ljwzTextBox5.Text = "";
            ghRadioButton.Checked = false;
            thRadioButton.Checked = false;
            thSerialNumberTextBox.Text = "";
            thProductTypeTextBox.Text = "";
            RadioButton1.Checked = false;
            RadioButton2.Checked = false;
            RadioButton3.Checked = false;
            RadioButton4.Checked = false;
            RadioButton5.Checked = false;
            RadioButton6.Checked = false;
            RadioButton7.Checked = false;
            RadioButton8.Checked = false;
            RadioButton9.Checked = false;
            RadioButton10.Checked = false;
            RadioButton11.Checked = false;
            RadioButton12.Checked = false;
            RadioButton13.Checked = false;
            bjLabel.Text = "";
            bzTextBox.Text = "";
            Label1.Text = "";
        }

        private void BindProductInfo(long productID)
        {
            try
            {
                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetApplicationProductByID(productID);
                blxxTextBox.Text = product.BLXX;
                bzTextBox.Text = product.Remark;
                rmaLabel.Text = product.ApplicationForm.ApplicationCode;
                rmaMaintainLabel.Text = product.ApplicationForm.ApplicationCode;
                typeLabel.Text = product.ProductType.ProductTypeName;
                serialLabel.Text = product.ProductSerialNumber;
                versionNOLbl.Text = product.ProductVersionNumber;
                versionNUmberLabel.Text = product.ProductVersionNumber;
                purchaseTimeLbl.Text = product.ProductPurchaseDateTime.Value.ToString("yyyy-MM-dd");
                wxwcrqLabel.Text = product.RepairCompleteDateTime != null ? Convert.ToDateTime(product.RepairCompleteDateTime).ToString("yyyy-MM-dd") : DateTime.Now.ToString("yyyy-MM-dd");

                /// Chen Pu: 2010-06-02 报价信息未能显示            
                if (!product.QuatationForm.IsLoaded)
                {
                    product.QuatationForm.Load();
                }
                if (product.QuatationForm != null && product.QuatationForm.Count > 0)
                {
                    double cost = 0;
                    int index = 1;
                    foreach (QuatationForm quatation in product.QuatationForm)
                    {
                        cost += quatation.Cost;

                        switch (index)
                        {
                            case 1:
                                blljTextBox1.Text = quatation.AccessoryName;
                                break;
                            case 2:
                                blljTextBox2.Text = quatation.AccessoryName;
                                break;
                            case 3:
                                blljTextBox3.Text = quatation.AccessoryName;
                                break;
                            case 4:
                                blljTextBox4.Text = quatation.AccessoryName;
                                break;
                            case 5:
                                blljTextBox5.Text = quatation.AccessoryName;
                                break;
                        }
                        index++;
                    }
                    bjLabel.Text = string.Format("总金额:{0}", cost);

                    WXLJGridView.DataSource = product.QuatationForm;
                    WXLJGridView.DataBind();
                }
                else
                {
                    bjLabel.Text = "未报价";
                }

                if (!string.IsNullOrEmpty(product.ChangeType))
                {
                    if (product.ChangeType.Equals("更换"))
                    {
                        ghRadioButton.Checked = true;
                    }
                    if (product.ChangeType.Equals("替换"))
                    {
                        thRadioButton.Checked = true;
                    }
                }

                if (!string.IsNullOrEmpty(product.ReplaceProductSerialNumber))
                {
                    thSerialNumberTextBox.Text = product.ReplaceProductSerialNumber;
                }

                if (!string.IsNullOrEmpty(product.ReplaceProductType))
                {
                    thProductTypeTextBox.Text = product.ReplaceProductType;
                }

                if (!string.IsNullOrEmpty(product.ReplaceProductVersion))
                {
                    versionDDL.SelectedValue = product.ReplaceProductVersion;
                }

                if (!string.IsNullOrEmpty(product.RepairAccessory))
                {
                    InitialRepaireAccessory(product.RepairAccessory);
                }

                if (!string.IsNullOrEmpty(product.AccessoryPlace))
                {
                    InitialAccessoryPlace(product.AccessoryPlace);
                }

                if (!string.IsNullOrEmpty(product.ReasonToProblem))
                {
                    InitializeBLYY(product.ReasonToProblem);
                }

                if (!product.ProblemAnalyzeReference.IsLoaded)
                {
                    product.ProblemAnalyzeReference.Load();
                }

                if (product.ProblemAnalyze != null)
                {
                    InitializeProblemAnalyze(product.ProblemAnalyze);
                }

                InitialProductVersion();
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::BindProductInfo");
                throw ex;
            }
        }        

        private void InitializeProblemAnalyze(ProblemAnalyze problemAnalyze)
        {
            SetProblemAnalyzeA(problemAnalyze.A);
            SetProblemAnalyzeB(problemAnalyze.B);
            SetProblemAnalyzeC(problemAnalyze.C);
            SetProblemAnalyzeD(problemAnalyze.D);
            SetProblemAnalyzeE(problemAnalyze.E);
        }

        private void InitialProductVersion()
        {
            ProductClassService classService = new ProductClassService();
            versionDDL.DataSource = classService.GetVersions();
            versionDDL.DataTextField = "Name";
            versionDDL.DataValueField = "Name";
            versionDDL.DataBind();
        }

        private void InitialAccessoryPlace(string accessoryPlace)
        {
            string[] accessorys = accessoryPlace.Split(';');
            for (int i = 0; i < accessorys.Count(); i++)
            {
                switch (i)
                {
                    case 0:
                        ljwzTextBox1.Text = accessorys[i];
                        break;
                    case 1:
                        ljwzTextBox2.Text = accessorys[i];
                        break;
                    case 2:
                        ljwzTextBox3.Text = accessorys[i];
                        break;
                    case 3:
                        ljwzTextBox4.Text = accessorys[i];
                        break;
                    case 4:
                        ljwzTextBox5.Text = accessorys[i];
                        break;
                }
            }
        }

        private void InitializeBLYY(string blyy)
        {
            string[] blyyArray = blyy.Split(';');
            for (int i = 0; i < blyyArray.Count(); i++)
            {
                switch (i)
                {
                    case 0:
                        blyyRadioButtonList1.SelectedValue = blyyArray[i];
                        break;
                    case 1:
                        blyyRadioButtonList2.SelectedValue = blyyArray[i];
                        break;
                    case 2:
                        blyyRadioButtonList3.SelectedValue = blyyArray[i];
                        break;
                    case 3:
                        blyyRadioButtonList4.SelectedValue = blyyArray[i];
                        break;
                    case 4:
                        blyyRadioButtonList4.SelectedValue = blyyArray[i];
                        break;
                }
            }
        }

        private void InitialRepaireAccessory(string accessory)
        {
            string[] accessorys = accessory.Split(';');
            for (int i = 0; i < accessorys.Count(); i++)
            {
                switch (i)
                {
                    case 0:
                        blljTextBox1.Text = accessorys[i];
                        break;
                    case 1:
                        blljTextBox2.Text = accessorys[i];
                        break;
                    case 2:
                        blljTextBox3.Text = accessorys[i];
                        break;
                    case 3:
                        blljTextBox4.Text = accessorys[i];
                        break;
                    case 4:
                        blljTextBox5.Text = accessorys[i];
                        break;
                }
            }
        }        

        private string ValidateMaintain()
        {
            string result = string.Empty;
            if (string.IsNullOrEmpty(blxxTextBox.Text))
            {
                result += "请输入不良现象。";
            }
            if (ghRadioButton.Checked == false && thRadioButton.Checked == false)
            {
                if (RadioButton10.Checked == false)
                {
                    ///朱经理 2010-06-02 7:21:09
                    ///维修记录 当选择T05, retest ok ,P08 电源时不需要填写零件位置
                    //if (string.IsNullOrEmpty(getLJWZ()) &&
                    //    (blyyRadioButtonList1.SelectedIndex > 1 ||
                    //     blyyRadioButtonList2.SelectedIndex > 1 ||
                    //     blyyRadioButtonList3.SelectedIndex > 1 ||
                    //     blyyRadioButtonList4.SelectedIndex > 1))
                    //{
                    //    result += "请输入零件位置。";
                    //}
                    //if (string.IsNullOrEmpty(getBLYY()))
                    //{
                    //    result += "请输入不良原因。";
                    //}
                    if (string.IsNullOrEmpty(getWXLJ()))
                    {
                        result += "请输入维修零件。";
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(blljTextBox1.Text))
                        {
                            if (blyyRadioButtonList1.SelectedItem == null)
                            {
                                result += "请选择第1个零件的不良原因";
                            }
                            else if (string.IsNullOrEmpty(ljwzTextBox1.Text) && blyyRadioButtonList1.SelectedIndex != 2)
                            {
                                result += "请输入第1个零件的维修位置";
                            }
                        }

                        if (!string.IsNullOrEmpty(blljTextBox2.Text))
                        {
                            if (blyyRadioButtonList2.SelectedItem == null)
                            {
                                result += "请选择第2个零件的不良原因";
                            }
                            else if (string.IsNullOrEmpty(ljwzTextBox2.Text) && blyyRadioButtonList2.SelectedIndex != 2)
                            {
                                result += "请输入第2个零件的维修位置";
                            }
                        }

                        if (!string.IsNullOrEmpty(blljTextBox3.Text))
                        {
                            if (blyyRadioButtonList3.SelectedItem == null)
                            {
                                result += "请选择第3个零件的不良原因";
                            }
                            else if (string.IsNullOrEmpty(ljwzTextBox3.Text) && blyyRadioButtonList3.SelectedIndex != 2)
                            {
                                result += "请输入第3个零件的维修位置";
                            }
                        }

                        if (!string.IsNullOrEmpty(blljTextBox4.Text))
                        {
                            if (blyyRadioButtonList4.SelectedItem == null)
                            {
                                result += "请选择第4个零件的不良原因";
                            }
                            else if (string.IsNullOrEmpty(ljwzTextBox4.Text) && blyyRadioButtonList4.SelectedIndex != 2)
                            {
                                result += "请输入第4个零件的维修位置";
                            }
                        }

                        if (!string.IsNullOrEmpty(blljTextBox5.Text))
                        {
                            if (blyyRadioButtonList5.SelectedItem == null)
                            {
                                result += "请选择第5个零件的不良原因";
                            }
                            else if (string.IsNullOrEmpty(ljwzTextBox5.Text) && blyyRadioButtonList5.SelectedIndex != 2)
                            {
                                result += "请输入第5个零件的维修位置";
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(getProblemAnalyzeA()) && string.IsNullOrEmpty(getProblemAnalyzeB()) && string.IsNullOrEmpty(getProblemAnalyzeC()) && string.IsNullOrEmpty(getProblemAnalyzeD()) && string.IsNullOrEmpty(getProblemAnalyzeE()))
                    {
                        result += "请输入故障分析";
                    }
                }
            }

            return result;
        }

        private string getLJWZ()
        {
            string ljwz = string.Empty;
            if (!string.IsNullOrEmpty(ljwzTextBox1.Text))
            {
                ljwz += ljwzTextBox1.Text;
            }
            if (!string.IsNullOrEmpty(ljwzTextBox2.Text))
            {
                if (!string.IsNullOrEmpty(ljwz))
                {
                    ljwz += ";";
                }
                ljwz += ljwzTextBox2.Text;
            }
            if (!string.IsNullOrEmpty(ljwzTextBox3.Text))
            {
                if (!string.IsNullOrEmpty(ljwz))
                {
                    ljwz += ";";
                }
                ljwz += ljwzTextBox3.Text;
            }
            if (!string.IsNullOrEmpty(ljwzTextBox4.Text))
            {
                if (!string.IsNullOrEmpty(ljwz))
                {
                    ljwz += ";";
                }
                ljwz += ljwzTextBox4.Text;
            }
            if (!string.IsNullOrEmpty(ljwzTextBox5.Text))
            {
                if (!string.IsNullOrEmpty(ljwz))
                {
                    ljwz += ";";
                }
                ljwz += ljwzTextBox5.Text;
            }
            return ljwz;
        }

        private string getWXLJ()
        {
            string wxlj = string.Empty;
            if (!string.IsNullOrEmpty(blljTextBox1.Text))
            {
                wxlj += blljTextBox1.Text;
            }
            if (!string.IsNullOrEmpty(blljTextBox2.Text))
            {
                if (!string.IsNullOrEmpty(wxlj))
                {
                    wxlj += ";";
                }

                wxlj += blljTextBox2.Text;
            }
            if (!string.IsNullOrEmpty(blljTextBox3.Text))
            {
                if (!string.IsNullOrEmpty(wxlj))
                {
                    wxlj += ";";
                }

                wxlj += blljTextBox3.Text;
            }
            if (!string.IsNullOrEmpty(blljTextBox4.Text))
            {
                if (!string.IsNullOrEmpty(wxlj))
                {
                    wxlj += ";";
                }

                wxlj += blljTextBox4.Text;
            }
            if (!string.IsNullOrEmpty(blljTextBox5.Text))
            {
                if (!string.IsNullOrEmpty(wxlj))
                {
                    wxlj += ";";
                }

                wxlj += blljTextBox5.Text;
            }

            return wxlj;
        }

        private string getBLYY()
        {
            string blyy = string.Empty;
            if (blyyRadioButtonList1.SelectedItem != null)
            {
                if (!string.IsNullOrEmpty(blyy))
                {
                    blyy += ";";
                }
                blyy += blyyRadioButtonList1.SelectedValue;
            }
            if (blyyRadioButtonList2.SelectedItem != null)
            {
                if (!string.IsNullOrEmpty(blyy))
                {
                    blyy += ";";
                }
                blyy += blyyRadioButtonList2.SelectedValue;
            }
            if (blyyRadioButtonList3.SelectedItem != null)
            {
                if (!string.IsNullOrEmpty(blyy))
                {
                    blyy += ";";
                }
                blyy += blyyRadioButtonList3.SelectedValue;
            }
            if (blyyRadioButtonList4.SelectedItem != null)
            {
                if (!string.IsNullOrEmpty(blyy))
                {
                    blyy += ";";
                }
                blyy += blyyRadioButtonList4.SelectedValue;
            }
            if (blyyRadioButtonList5.SelectedItem != null)
            {
                if (!string.IsNullOrEmpty(blyy))
                {
                    blyy += ";";
                }
                blyy += blyyRadioButtonList5.SelectedValue;
            }

            return blyy;
        }

        #region for problem analyze

        private string getProblemAnalyzeE()
        {
            string eStr = string.Empty;
            if (RadioButton11.Checked)
            {
                eStr = RadioButton11.Text;
            }
            return eStr;
        }

        private void SetProblemAnalyzeE(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (value.Equals(RadioButton11.Text))
                {
                    RadioButton11.Checked = true;
                }
            }
        }

        private string getProblemAnalyzeD()
        {
            string dStr = string.Empty;
            if (RadioButton10.Checked)
            {
                dStr = RadioButton10.Text;
            }

            return dStr;
        }

        private void SetProblemAnalyzeD(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (value.Equals(RadioButton10.Text))
                {
                    RadioButton10.Checked = true;
                }
            }
        }

        private string getProblemAnalyzeC()
        {
            string cStr = string.Empty;
            if (RadioButton9.Checked)
            {
                cStr = RadioButton9.Text;
            }
            else if (RadioButton8.Checked)
            {
                cStr = RadioButton8.Text;
            }
            else if (RadioButton13.Checked)
            {
                cStr = RadioButton13.Text;
            }

            return cStr;
        }

        private void SetProblemAnalyzeC(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (value.Equals(RadioButton9.Text))
                {
                    RadioButton9.Checked = true;
                }
                if (value.Equals(RadioButton8.Text))
                {
                    RadioButton8.Checked = true;
                }
                if (value.Equals(RadioButton13.Text))
                {
                    RadioButton13.Checked = true;
                }
            }
        }

        private string getProblemAnalyzeB()
        {
            string bStr = string.Empty;
            if (RadioButton7.Checked)
            {
                bStr = RadioButton7.Text;
            }
            else if (RadioButton6.Checked)
            {
                bStr = RadioButton6.Text;
            }
            else if (RadioButton5.Checked)
            {
                bStr = RadioButton5.Text;
            }
            else if (RadioButton12.Checked)
            {
                bStr = RadioButton12.Text;
            }
            return bStr;
        }

        private void SetProblemAnalyzeB(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (value.Equals(RadioButton5.Text))
                {
                    RadioButton5.Checked = true;
                }
                if (value.Equals(RadioButton6.Text))
                {
                    RadioButton6.Checked = true;
                }
                if (value.Equals(RadioButton7.Text))
                {
                    RadioButton7.Checked = true;
                }
                if (value.Equals(RadioButton12.Text))
                {
                    RadioButton12.Checked = true;
                }
            }
        }

        private string getProblemAnalyzeA()
        {
            string aStr = string.Empty;
            if (RadioButton4.Checked)
            {
                aStr = RadioButton4.Text;
            }
            else if (RadioButton3.Checked)
            {
                aStr = RadioButton3.Text;
            }
            else if (RadioButton2.Checked)
            {
                aStr = RadioButton2.Text;
            }
            else if (RadioButton1.Checked)
            {
                aStr = RadioButton1.Text;
            }
            return aStr;
        }

        private void SetProblemAnalyzeA(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                if (value.Equals(RadioButton1.Text))
                {
                    RadioButton1.Checked = true;
                }
                if (value.Equals(RadioButton2.Text))
                {
                    RadioButton2.Checked = true;
                }
                if (value.Equals(RadioButton3.Text))
                {
                    RadioButton3.Checked = true;
                }
                if (value.Equals(RadioButton4.Text))
                {
                    RadioButton4.Checked = true;
                }
            }
        }

        #endregion
        #endregion

        #region for quotation
        protected void quotePriceLinkButton_Click(object sender, EventArgs e)
        {
            string productID = ((LinkButton)sender).CommandArgument;    
            try
            {
                InitialQuatationPanel(productID);
                BindAccessoryGridView(long.Parse(productID));
                quatationModalPopupExtender.Show();
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::quotePriceLinkButton_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息提取发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        // 保存报价信息
        protected void saveQuatationLnkBtn_Click(object sender, EventArgs e)
        {
            string changeLogContent = string.Format("");
            ChangeLogService changeLogService = new ChangeLogService();
            try
            {
                changeLogContent = string.Format("产品报价保存：FormNeedRepair::saveQuatationLnkBtn_Click");
                changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, hfproductID.Value, changeLogContent);

                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetApplicationProductByID(long.Parse(hfproductID.Value));
                if (!product.QuatationForm.IsLoaded)
                {
                    product.QuatationForm.Load();
                }
                // 如果有新建的报价零件，创建报价信息 QuatationForm
                if (!string.IsNullOrEmpty(TextBox1.Text) &&
                    !string.IsNullOrEmpty(TextBox2.Text))
                {
                    if (DropDownList1.SelectedIndex == 0)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('请您选择报价原因，然后再点击保存按钮！');", true);
                        quatationModalPopupExtender.Show();
                    }
                    else
                    {
                        QuatationForm form = new QuatationForm
                        {
                            AccessoryName = TextBox1.Text,
                            UnitPrice = Convert.ToDecimal(TextBox2.Text),
                            Cost = Convert.ToDouble(TextBox2.Text) * Convert.ToInt32(countDDL.SelectedValue),
                            Reason = DropDownList1.SelectedItem.Text,
                            Count = Convert.ToInt32(countDDL.SelectedValue),
                            CreateDate = DateTime.Now
                        };

                        changeLogContent = string.Format("产品报价添加：报价单号{0} FormNeedRepair::saveQuatationLnkBtn_Click", form.ID);
                        changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, hfproductID.Value, changeLogContent);

                        if (isBWBACheckBox.Checked)
                        {
                            form.IsBWBA = true;
                        }

                        form.ApplicationProduct = product;
                        service.AddQuatation(form);
                    }
                }
                // 更新产品报价信息：报价原因，不良现象， IsQuotePrice
                if (product.QuatationForm.Count > 0)
                {
                    if (DropDownList1.SelectedIndex == 0)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('请您选择报价原因，然后再点击保存按钮！');", true);
                        quatationModalPopupExtender.Show();
                    }
                    else
                    {
                        changeLogContent = string.Format("产品报价更新相关信息：报价单号 FormNeedRepair::saveQuatationLnkBtn_Click");
                        changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, hfproductID.Value, changeLogContent);

                        product.ReasonOfCost = DropDownList1.SelectedItem.Text;
                        product.BLXX = blxxTxtBox.Text;
                        product.IsQuotePrice = true;
                        //product.QuotationDateTime = DateTime.Now; // 2013.8.31 添加 // 2013.9.5 将报价日期移至当点击报价完毕时填写
                        service.UpdateProduct(product);

                        BindProduct();
                        ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('报价信息已成功保存，待完成该产品报价后，请点击该产品后的“报价完毕”按钮结束报价！');", true);
                    }
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('您未添加任何报价信息，不能保存，如要仅需关闭当前窗口，请点击关闭按钮！');", true);
                    quatationModalPopupExtender.Show();
                }
            }
            catch (Exception ex)
            {
                changeLogContent = string.Format("产品报价保存异常：异常{0}", ex.ToString());
                changeLogService.AddChangeLog(ChangeLogType.QuatationForm, hfproductID.Value, changeLogContent);

                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::saveQuatationLnkBtn_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息保存发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        //删除报价信息
        protected void deleteQuatationLnkBtn_Click(object sender, EventArgs e)
        {
            string changeLogContent = string.Format("");
            ChangeLogService changeLogService = new ChangeLogService();
            long quatationFormID = long.Parse(((LinkButton)sender).CommandArgument);
            try
            {
                ApplicationProductService service = new ApplicationProductService();
                service.DeleteQuatationFormByID(quatationFormID);

                changeLogContent = string.Format("产品报价删除：报价单号{0}", quatationFormID);
                changeLogService.AddChangeLog(ChangeLogType.QuatationForm, hfproductID.Value, changeLogContent);

                ApplicationProduct applicationProduct = service.GetApplicationProductByID(Convert.ToInt64(hfproductID.Value));
                if (!applicationProduct.QuatationForm.IsLoaded)
                {
                    applicationProduct.QuatationForm.Load();
                }
                if (applicationProduct.QuatationForm.Count == 0)
                {
                    applicationProduct.IsQuotePrice = false;
                    applicationProduct.QuotationDateTime = null;
                    applicationProduct.ReasonOfCost = "";
                    service.UpdateProduct(applicationProduct);
                }

                BindAccessoryGridView(long.Parse(hfproductID.Value));
            }
            catch (Exception ex)
            {
                changeLogContent = string.Format("产品报价删除异常：报价单号{0}，异常{1}", quatationFormID, ex.ToString());
                changeLogService.AddChangeLog(ChangeLogType.QuatationForm, hfproductID.Value, changeLogContent);

                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::deleteQuatationLnkBtn_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息保存发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        /// 朱经理 2010-6-2 7:45:07
        /// 还有 这个报价的收费原因里面 因为一个产品报价的原因就只能一个，请只显示一个
        private void InitialQuatationPanel(string productID)
        {
            try
            {
                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetApplicationProductByID(long.Parse(productID));
                serialNumberLabel.Text = product.ProductType.ProductTypeName;
                rmaLabel.Text = rmaCodeLabel.Text;
                hfproductID.Value = productID;
                versionNOLbl.Text = product.ProductVersionNumber;
                versionNUmberLabel.Text = product.ProductVersionNumber;
                TextBox1.Text = "";
                TextBox2.Text = "";
                isBWBACheckBox.Checked = false;

                if (!product.QuatationForm.IsLoaded)
                {
                    product.QuatationForm.Load();
                }
                if (product.QuatationForm != null && product.QuatationForm.Count > 0)
                {
                    DropDownList1.SelectedValue = product.QuatationForm.FirstOrDefault().Reason;
                }
                else
                {
                    DropDownList1.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::InitialQuatationPanel");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息提取发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        private void BindAccessoryGridView(long productID)
        {
            try
            {
                ApplicationProductService service = new ApplicationProductService();
                accessoryGridView.DataSource = service.GetQuatationFormByProductID(productID);
                accessoryGridView.DataBind();
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::BindAccessoryGridView");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息提取发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }

        // 报价-> 报价零件 绑定处理事件
        protected void accessoryGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            }
        }

        protected void addQuatationBtn_Click(object sender, EventArgs e)
        {
            string changeLogContent = string.Format("");
            ChangeLogService changeLogService = new ChangeLogService();

            try
            {
                string result = ValidateQuatation(TextBox1.Text, TextBox2.Text, DropDownList1.SelectedValue);
                if (string.IsNullOrEmpty(result))
                {
                    QuatationForm form = new QuatationForm
                    {
                        AccessoryName = TextBox1.Text,
                        Cost = Convert.ToDouble(TextBox2.Text) * Convert.ToInt32(countDDL.SelectedValue),
                        Reason = DropDownList1.SelectedItem.Text,
                        UnitPrice = Convert.ToDecimal(TextBox2.Text),
                        Count = Convert.ToInt32(countDDL.SelectedValue),
                        CreateDate = DateTime.Now
                    };
                    if (isBWBACheckBox.Checked)
                    {
                        form.IsBWBA = true;
                    }
                    else
                    {
                        form.IsBWBA = false;
                    }
                    
                    ApplicationProductService service = new ApplicationProductService();
                    form.ApplicationProduct = service.GetApplicationProductByID(long.Parse(hfproductID.Value));
                    service.AddQuatation(form);

                    changeLogContent = string.Format("产品报价添加：报价单号{0} FormNeedRepair::addQuatationBtn_Click", form.ID);
                    changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, hfproductID.Value, changeLogContent);

                    // Reset 报价单
                    TextBox1.Text = "";
                    TextBox2.Text = "";
                    isBWBACheckBox.Checked = false;
                    DropDownList1.SelectedIndex = 0;
                    BindAccessoryGridView(long.Parse(hfproductID.Value));
                }
            }
            catch (Exception ex)
            {
                changeLogContent = string.Format("产品报价异常：{0} FormNeedRepair::addQuatationBtn_Click", ex.ToString());
                changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, hfproductID.Value, changeLogContent);

                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::addQuatationBtn_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息保存发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }     
        

        //验证报价信息是否正确
        private string ValidateQuatation(string p, string p_2, string p_3)
        {
            string result = string.Empty;
            if (string.IsNullOrEmpty(p))
            {
                result += "没有输入零件\n";
            }
            if (string.IsNullOrEmpty(p_2))
            {
                result += "没有价格\n";
            }
            if (p_3.Equals("0"))
            {
                result += "请选择收费原因";
            }

            return result;
        }

        //获取零件信息
        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {
            try
            {
                int applicationID = Convert.ToInt32(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]);
                ApplicationService applicationService = new ApplicationService();
                ApplicationForm application = applicationService.GetApplicationFormByID(applicationID);
                if (!application.ServiceStationReference.IsLoaded)
                {
                    application.ServiceStationReference.Load();
                }

                AccessoryService service = new AccessoryService();
                Accessory acc = service.GetAccessoryByName(TextBox1.Text);
                if (acc != null)
                {
                    TextBox2.Text = acc.Price.ToString();
                    tipLabel.Text = "";
                }
                else
                {
                    tipLabel.Text = "库存中没有该零件";
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::TextBox1_TextChanged");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('信息保存发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }               

        #endregion

        #region for spare part apply

        protected void sparePartLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                spaTextBox.Text = "";
                spaCheckResultTxtBox.Text = "";
                sspTipLabel.Visible = false;
                sparePartModalPopupExtender.Show();
                hfAppliyProductID.Value = ((LinkButton)sender).CommandArgument;
                SparePartApplyService sspService = new SparePartApplyService();
                SparePartApplyForm sspForm = sspService.GetSparePartApplyByApplicationProductID(long.Parse(hfAppliyProductID.Value));
                // 如果已经申请过备件，现在所申请的信息
                if (sspForm != null)
                {
                    if (!sspForm.ApplicationProductReference.IsLoaded)
                    {
                        sspForm.ApplicationProductReference.Load();
                    }
                    if (!sspForm.ApplicationProduct.ProductTypeReference.IsLoaded)
                    {
                        sspForm.ApplicationProduct.ProductTypeReference.Load();
                    }

                    spaTextBox.Text = sspForm.Reason;
                    spaCheckResultTxtBox.Text = sspForm.ApplicationProduct.Remark;

                    sspTipLabel.Visible = true;
                    sspTipLabel.Text = string.Format(WebConfigurationManager.AppSettings["SSPTip"], sspForm.ApplyTime.Value.ToString("yyyy-MM-dd"), sspForm.ApplicationProduct.ProductType.ProductTypeName);
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::sparePartLinkButton_Click");
                throw ex;
            }
        }

        protected void sparePartApplyLinkButton_Click(object sender, EventArgs e)
        {
            string changeLogContent = string.Format("");
            ChangeLogService changeLogService = new ChangeLogService();
            try
            {
                if (!string.IsNullOrEmpty(spaTextBox.Text))
                {
                    SparePartApplyService service = new SparePartApplyService();
                    service.AddSparePartApplyForm(hfAppliyProductID.Value, spaTextBox.Text,
                        ContextService.CurrentAccount.UserID, spaCheckResultTxtBox.Text);

                    changeLogContent = string.Format("备件申请创建:FormNeedRepair.aspx::sparePartApplyLinkButton_Click");
                    changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, hfAppliyProductID.Value, changeLogContent); 

                    // Reset表单
                    spaTextBox.Text = "";
                    spaCheckResultTxtBox.Text = "";

                    BindProduct();
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('提交失败，请输入备件申请原因。');", true);
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::sparePartApplyLinkButton_Click");

                changeLogContent = string.Format("备件申请创建异常:FormNeedRepair.aspx::sparePartApplyLinkButton_Click，{0}", ex.ToString());
                changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, hfAppliyProductID.Value, changeLogContent);

                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('提交失败，发生错误：{0}，请通知管理员。');", ex.Message), true);
            }
        }

        #endregion

        #region for upgrade

        protected void upGridLinkButton_Click(object sender, EventArgs e)
        {
            UpgradeCheckResultTxtBox.Text = "";
            upgradeReasonTextBox.Text = "";
            upgradeModalPopupExtender.Show();
            hfAppliyProductID.Value = ((LinkButton)sender).CommandArgument;
        }

        protected void applyUpgradeLinkButton_Click(object sender, EventArgs e)
        {
            string changeLogContent = string.Format("");
            ChangeLogService changeLogService = new ChangeLogService();
            try
            {
                if (!string.IsNullOrEmpty(upgradeReasonTextBox.Text))
                {
                    LinkButton applyUpgradeLinkButton = sender as LinkButton;
                    ApplicationProductService applicationProductService = new ApplicationProductService();
                    ApplicationProduct applicationProduct = applicationProductService.GetApplicationProductByID(Convert.ToInt64(hfAppliyProductID.Value));
                    if (!applicationProduct.UserReference.IsLoaded)
                    {
                        applicationProduct.UserReference.Load();
                    }
                    UpgradeService service = new UpgradeService();
                    service.AddUpgradeForm(hfAppliyProductID.Value, upgradeReasonTextBox.Text, applicationProduct.User.UserID,
                        sendWayDropDownList.Text, UpgradeCheckResultTxtBox.Text);

                    changeLogContent = string.Format("升级申请创建:FormNeedRepair.aspx::applyUpgradeLinkButton_Click");
                    changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, hfAppliyProductID.Value, changeLogContent); 

                    BindProduct();
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('提交失败，请填写升级原因。');", true);
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::applyUpgradeLinkButton_Click");

                changeLogContent = string.Format("升级申请创建异常:FormNeedRepair.aspx::applyUpgradeLinkButton_Click 异常:{0}", ex.ToString());
                changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, hfAppliyProductID.Value, changeLogContent);

                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('提交失败，发生错误：{0}，请通知管理员。');", ex.Message), true);
            }
        }
        #endregion

        #region for return to factory

        protected void returnTofactoryLinkButton_Click(object sender, EventArgs e)
        {
            ReturnFactoryFlowNOLbl.Text = RunningNumberService.GenerateReturnToFactoryRunningNumber("");

            returnFactoryModalPopupExtender.Show();
            hfAppliyProductID.Value = ((LinkButton)sender).CommandArgument;
        }

        protected void returnFactoryLinkButton_Click(object sender, EventArgs e)
        {
            string changeLogContent = string.Format("");
            ChangeLogService changeLogService = new ChangeLogService();
            try
            {
                if (!string.IsNullOrEmpty(returntofactoryblxxTextBox.Text.Trim()) &&
                    !string.IsNullOrEmpty(returnFactoryTextBox.Text.Trim()))
                {
                    ReturnToFactoryService rtfService = new ReturnToFactoryService();
                    rtfService.AddRetrunToFactoryForm(long.Parse(hfAppliyProductID.Value), returntofactoryblxxTextBox.Text,
                        returnFactoryTextBox.Text, ReturnFactoryFlowNOLbl.Text, returnFactoryTextBox.Text);

                    changeLogContent = string.Format("返厂申请创建:FormNeedRepair.aspx::returnFactoryLinkButton_Click");
                    changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, hfAppliyProductID.Value, changeLogContent);

                    BindProduct();
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('提交失败，请正确填写”不良现象“和”要求“。');", true);
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::returnFactoryLinkButton_Click");

                changeLogContent = string.Format("返厂申请创建异常:FormNeedRepair.aspx::returnFactoryLinkButton_Click 异常:{0}", ex.ToString());
                changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, hfAppliyProductID.Value, changeLogContent);

                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('提交失败，发生错误：{0}，请通知管理员。');", ex.Message), true);
            }            
        }

        #endregion

        #region 不维修产品
        //不维修产品链接点击处理事件
        protected void noRepairInfoLnkBtn_Click(object sender, EventArgs e)
        {
            noRepairRecordModal.Show();
        }

        // 不维修产品 绑定处理事件
        protected void NoRepareInfoGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.DataItem != null)
                {
                    e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                    e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                    ((Label)e.Row.FindControl("IDLbl2")).Text = (e.Row.RowIndex + 1).ToString();

                    ApplicationProduct product = e.Row.DataItem as ApplicationProduct;
                    Literal isDecitdeToRepair = (Literal)e.Row.FindControl("isDecideToRepairLiteral2");
                    Literal isQuotePrice = (Literal)e.Row.FindControl("isQuotePriceLiteral2");

                    if (product.IsDecideToRepair.HasValue)
                    {
                        if (product.IsDecideToRepair == true)
                        {
                            isDecitdeToRepair.Text = "确认维修";
                            //maintainLinkButton.Enabled = true;
                        }
                        else
                        {
                            isDecitdeToRepair.Text = "不维修";
                        }
                    }

                    if (product.IsQuotePrice.HasValue && product.IsQuotePrice == true)
                    {
                        isQuotePrice.Text = "已报价";
                    }
                    else
                    {
                        isQuotePrice.Text = "未报价";
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::ProductGridView_RowDataBound2");
                throw ex;
            }
        }
        #endregion

        #region 归还备件
        // 归还备件信息 链接点击处理事件
        protected void sparePartInfoLnkBtn_Click(object sender, EventArgs e)
        {
            sparePartRtnModal.Show();
        }

        // 归还备件信息 绑定处理事件
        protected void SparePartRtnInfoGridView_RowDataBound3(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                ((Label)e.Row.FindControl("IDLbl3")).Text = (e.Row.RowIndex + 1).ToString();
            }
        }

        // 归还备件信息->备件流水号 点击处理事件
        protected void idlnk_Click(object sender, EventArgs e)
        {
            LinkButton lnkBtn = sender as LinkButton;
            string url = string.Format("SparePartApplyDisagree.aspx?SPAREPARTAPPLY_ID={0}", lnkBtn.CommandArgument);
            Response.Redirect(url);
        }
        #endregion

        #region 产品图片
        // 上传产品图片
        protected void uploadButton_Click(object sender, EventArgs e)
        {
            try
            {
                string fileType = string.Empty;
                string fileName = string.Empty;
                string fileNameOnServer = string.Empty;
                if (fileUploadPicture.HasFile)
                {
                    fileType = fileUploadPicture.FileName.Substring(fileUploadPicture.FileName.LastIndexOf("."));
                    fileName = fileUploadPicture.FileName;
                    fileNameOnServer = Guid.NewGuid() + fileType;
                    fileUploadPicture.SaveAs(Server.MapPath("Picture/" + fileNameOnServer));
                }
                ApplicationService service = new ApplicationService();
                ApplicationForm form = service.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                ApplicationPicture picture = new ApplicationPicture
                {
                    PictureName = fileName,
                    PictureNameOnServer = fileNameOnServer,
                    Type = (int)PictureType.MaintainProduct,
                    UploadPerson = ContextService.CurrentAccount.UserID
                };
                form.ApplicationPicture.Add(picture);
                service.UpdateApplication(form);
                BindProduct();
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "FormNeedRepair::uploadButton_Click");
                throw ex;
            }
        }
        #endregion        
    }
}